<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;

use App\Models\Organization;



class OrganizationsMembers extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $table = 'organizations_members';

    /**
     * 根据ID获取数据
     *
     * @param $id
     * @param mixed $columns
     * @return array|Builder
     */
    public static function getDataByID($id, string $columns = ''){
        $data = self::query();
        if($columns){
            $data->find($id,$columns);
            return $data;
        }
        $val = $data->find($id);
        $status_show =  getStatusValue($val['status']);
        return [
            'id'=>$val['id'],
            'name'=>$val['name'],
            'status'=>$val['status'],
            'sort'=>$val['sort'],
            'status_show'=>$status_show,
            'crated_at'=>Carbon::parse($val['crated_at'])->toDateTimeString(),
            'updated_at'=>Carbon::parse($val['updated_at'])->toDateTimeString(),
        ];
    }

    /**
     * 申请加入组织
     *
     * @param $userInfo
     * @param $organization_id
     * @return array|Builder
     */
    public static function applicationJoin($userInfo,$organization_id){
        $user_id = $userInfo->id;
        if (empty($user_id)) {
            return ['data'=>[],'msg'=>'请先登录！','code'=>'201'];
        }

        $checkHave = self::query()->where([
            ['organization_id', '=', $organization_id],
            ['user_id', '=', $user_id],
            ['status', '>', 0]
        ])->first('id as om_id');
        // var_dump($checkHave['om_id']);exit();
        if ($checkHave['om_id']>0) {
            return ['data'=>[],'msg'=>'您已经加入或等待审核中，请耐心等待！','code'=>'2001'];
        }

        $organizationInfo = Organization::getDataByID($organization_id);

        if (empty($organizationInfo)) {
            return ['data'=>[],'msg'=>'组织不存在或已删除！','code'=>'2002'];
        }

        $insertArr = [
            'organization_id'=>$organization_id,
            'user_id'=>$user_id,
            'is_admin'=>0,
            'status'=>1,
            'created_at'=>date('Y-m-d H:i:s'),
        ];

        $omId = self::query()->insertGetId($insertArr);

        if($omId<1){
            return ['data'=>[],'msg'=>'申请失败，请稍后再试！','code'=>'2000'];
        }

        return [
            'msg'=>'ok',
            'code'=>'200',
            'om_id'=>$omId
        ];

    }

    /**
     * 修改申请加入组织状态
     *
     */
    public static function updateJoinStatus($om_id,$status){

        if (empty($om_id)) {
            return ['data'=>[],'msg'=>'申请记录不存在！','code'=>'2000'];
        }

        if (empty($status)) {
            $status = 0;
        }

        $userInfo = auth('api')->user();
        $userId  = $userInfo['id'];

        // 判断是否有权限
        $checkHave = self::query()->where([
            ['id', '=', $om_id]
        ])->first();
        if( $checkHave['organization_id'] ){

            $checkAdmin = self::query()->where([
                ['organization_id', '=', $checkHave['organization_id']],
                ['is_admin', '=',1],
                ['user_id', '=',$userId]
            ])->first();

            if($checkAdmin){

                $result = self::query()->where('id', $om_id)->update(['status' => $status,'updated_at'=>date('Y-m-d H:i:s')]);

            }else{
                return ['data'=>[],'msg'=>'权限不足！','code'=>'2000'];
            }
        }else{
            return ['data'=>[],'msg'=>'申请记录不存在！','code'=>'2000'];
        }



        // if (!$result) {
        //     return ['data'=>[],'msg'=>'次用户已被审核！','code'=>'2001'];
        // }

        return [
            'msg'=>'ok',
            'code'=>'200',
            'status'=>$status
        ];
    }

    /**
     * 查询组织成员列表
     * @param $is_all true 包含申请中成员
     *
     */
    public static function getMembersList($organization_id,$is_all = false,$is_examine=false){

        if (empty($organization_id)) {
            return ['data'=>[],'msg'=>'请确认组织是否正确！','code'=>'2000'];
        }


        if ($is_all) {
            $where[] =['organizations_members.status', '>', 0];
        }else{
            $where[] =['organizations_members.status', '=', 2];
        }

        if ($is_examine) {
            unset($where);
            $where[] =['organizations_members.status', '=', 1];
        }

        $where[] = ['organizations_members.organization_id', '=', $organization_id];

        $field = [
            'users.id as user_id',
            'users.username',
            'users.openid',
            'users.unionid',
            'users.avatar',
            'users.school_time',
            'users.major',
            'organizations_members.is_admin',
            'organizations_members.status as o_status',
            'organizations_members.id as om_id',

        ];
        $data = self::query()
            ->join('users', 'organizations_members.user_id', '=', 'users.id')
            ->where($where)
            ->distinct('users.id')
            ->select($field)
            ->get();

        if(!empty($data)){
            foreach($data as $key=>$val){
                $data[$key]['avatar'] =  getImageUrl($val['avatar']);
            }
        }


        return [
            'msg'=>'ok',
            'code'=>'200',
            'data'=>$data
        ];
    }


    public static function getMyMembersList($userId){


        $where[] = ['organizations_members.user_id', '=', $userId];

        $field = [
            'organizations_members.id',
            'organizations_members.organization_id',
            'organizations.avatar as org_avatar',
            'organizations.name as name',
            'organizations_members.is_admin',
            'organizations_members.status as o_status'
        ];

        $data = self::query()
            ->leftjoin('organizations', 'organizations_members.organization_id', '=', 'organizations.id')
         //   ->leftjoin('users', 'organizations_members.user_id', '=', 'users.id')
            ->where($where)
            ->where(['organizations_members.status'=>2])
            ->latest('is_admin')
            ->latest('id')
            ->distinct('users.id')
            ->select($field)
            ->get();

        return $data;
    }


    public  static  function  formatListDataOne($data)
    {

        if($data){
            $data = json_encode($data);
            $data = json_decode($data,true);

            $data['status_show'] = self::getStatusValue($data['o_status'],true);

            $image = $data['org_avatar'];
            $image_path = 'https://alumnus.biaoxufilm.com/storage/file/20231129210449.png';
            if($image){
                $image_path = empty( $data['org_avatar']) ? $image_path :getImageUrl($data['org_avatar']);
                $image_show = '<img width="60" height="60" src="'.$image_path.'">';
            }

            $data['number'] = self::query()->where(['organization_id'=>$data['organization_id'],'status'=>2])->count();
            $data['org_avatar_path'] = $image_path??"";
            $data['org_avatar_show'] = $image_show??"";
        }
        return $data;
    }

    private static function getStatusValue($status)
    {
        return self::getSignUpStatusArray()[$status];
    }
    public static function getSignUpStatusArray(): array
    {
        return [
            0=>'已删除',
            1=>'申请中',
            2=>'已通过',
            3=>'被拒绝',
        ];
    }


    public  function orgList(): \Illuminate\Database\Eloquent\Relations\HasOne
    {

        return $this->hasOne(Organization::class,'id','organization_id');//->where('status',2) ;
    }

    public static function getApplicationList($organization_id){

        if (empty($organization_id)) {
            return ['data'=>[],'msg'=>'请确认组织是否正确！','code'=>'2000'];
        }


        $where[] = ['organizations_members.organization_id', '=', $organization_id];
        $where[] = ['organizations_members.status', '=', 1];
        $where[] = ['organizations_members.is_admin', '=', 0];

        $field = [
            'organizations_members.id as om_id',
            'users.id as user_id',
            'users.name',
            'users.avatar',
            'users.school_time',
            'users.major',
        ];
        $data = self::query()
            ->join('users', 'organizations_members.user_id', '=', 'users.id')
            ->where($where)
            ->distinct('users.id')
            ->select($field)
            ->get();
        return $data;
    }
}
